#!/usr/bin/env python
# encoding=utf-8

from flask import *
from flask.ext.login import login_user, logout_user, login_required, current_user

from . import auth
from .forms import *
from ..logger import *
from ..models import User, UserLog


@auth.route('/login', methods=['GET', 'POST'])
def login():
    if current_user.is_authenticated:
        flash(u'您当前已经登录，请勿重复操作')
        return redirect(url_for('web.index'))
    form = SigninForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data

        user = User.query(username=username)
        if user and user.verify_password(password):
            login_user(user, form.remember.data)
            log(UserLog(LOGIN_EVENT, 'success'))
            return redirect(request.args.get('next', '')) or url_for('web.index')
        log(UserLog(LOGIN_EVENT, 'fail'))
        flash(u'用户名密码不匹配')
    return render_template('auth/login.html', form=form, title=u'登录')


@auth.route('/signup', methods=['GET', 'POST'])
def signup():
    if current_user.is_authenticated:
        flash(u'您当前已经登录')
        return redirect(url_for('web.index'))
    form = SignupForm()
    if form.validate_on_submit():
        username = form.username.data
        password = form.password.data
        phone = form.phone.data

        if User.query(username=username):
            flash(u'用户已经存在')
            return render_template('auth/signup.html', form=form, title=u'注册')
        if User.query(phone=phone):
            flash(u'手机号码已经被注册')
            return render_template('auth/signup.html', form=form, title=u'注册')

        user = User(username=username, password=password, phone=phone)
        user.save()

        log(UserLog(SIGNUP_EVENT, user.uuid))
        flash(u'注册成功')
        return redirect(url_for('auth.login'))
    return render_template('auth/signup.html', form=form, title=u'注册')


@auth.route('/logout')
@login_required
def logout():
    logout_user()
    log(UserLog(LOGOUT_EVENT, None))
    flash(u'您已经成功退出。')
    return redirect(url_for('auth.login'))
